package com.samp.tools.tika;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;

/**
 * 也可参数solr的dih中的：TikaEntityProcessor
 * @author EX-WANWEI001
 *
 */
public class Demo {
	
	public static void getTextFronPDF() throws IOException, SAXException, TikaException{
		   //构建InputStream来读取数据
		   InputStream  input=new FileInputStream(new File("D:\\temp\\pdf\\统一搜索AI接口文档0730.docx"));//可以写文件路径，pdf，word，html等
		   BodyContentHandler textHandler=new BodyContentHandler();
		   Metadata matadata=new Metadata();//Metadata对象保存了作者，标题等元数据
		   Parser parser=new  AutoDetectParser();//当调用parser，AutoDetectParser会自动估计文档MIME类型，此处输入pdf文件，因此可以使用PDFParser
		   ParseContext context=new ParseContext();
		   parser.parse(input, textHandler, matadata, context);//执行解析过程
		   input.close();
		   System.out.println("Title: "+matadata.get(Metadata.TITLE));
		   System.out.println("Type: "+matadata.get(Metadata.TYPE));
		   System.out.println("Body: "+textHandler.toString());//从textHandler打印正文
	   }
	
	public static void main(String[] args) {
		try {
			getTextFronPDF();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (TikaException e) {
			e.printStackTrace();
		}
	}
}
